package serialport


import event.ChargeStatusChangedEvent
import ext.action
import ext.log
import ext.toHexString
import manager.AppManager
import manager.PayManager
import org.greenrobot.eventbus.EventBus


object MDBPortManager : Thread() {
    var mdbPort: Port? = null
    var runnFlag = false

    init {
        try {
            mdbPort = Port(AppManager.mdbPortName)
            log("MDB串口:${AppManager.mdbPortName}-打开成功")
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    fun write(bytes: ByteArray) {
        mdbPort?.write(bytes)
        log(bytes.toHexString(), "MDB发送")
    }

    override fun start() {
        runnFlag = true
        super.start()
    }

    private fun onParse(bytes: ByteArray) {
        log("${bytes.toHexString()}", "MDB数据接收")

        when (bytes.action()) {
            0x05 -> { // 预扣款成功
                if (!PayManager.webPayFlag) {
                    EventBus.getDefault().post(ChargeStatusChangedEvent(ChargeStatusChangedEvent.OK))
                }
                PayManager.onPay()
            }

            0x06 -> { // 无法扣款
                if (!PayManager.webPayFlag) {
                    EventBus.getDefault().post(ChargeStatusChangedEvent(ChargeStatusChangedEvent.ERROR))
                }
                PayManager.onError()
                PayManager.cancel()
            }
        }
    }

    private fun exec() {
        val pkg = mdbPort!!.readPackage()
        onParse(pkg)
    }

    override fun run() {
        if (mdbPort == null) {
            return
        }

        while (runnFlag) {
            try {
                exec()
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }

}
